import flash.events.*;

import generated.webservices.*;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.*;
import mx.rpc.events.FaultEvent;

private var mWS: MediaWS = new MediaWS(null, DataController.GetMediaWsUrl());

[Bindable]
private var users: ArrayCollection;
[Bindable]
private var tags: TagTreeInfo;
[Bindable]
private var objects: ArrayOfMObject;

[Bindable]
private var objectsByTag: ArrayOfMObject;

private function init(): void {
	mWS.addMediaWSFaultEventListener(callBackError);
	mWS.addgetUsersEventListener(callBackGetUsers);
	mWS.addgetTagTreeEventListener(callBackGetTagTree);
	mWS.addgetAlbumObjectsEventListener(callBackGetAlbumObjects);
	mWS.addgetObjectsByTagEventListener(callBackGetObjectsByTag);
	
	tabNavMain.addEventListener(IndexChangedEvent.CHANGE, tabIndexChanged);
	treeTags.addEventListener(ListEvent.CHANGE, refreshObjectsByTags);
	cbIncludeSubTags.addEventListener(Event.CHANGE, refreshObjectsByTags);
	btnRefreshTagTree.addEventListener(MouseEvent.CLICK, refreshTags);
	listObjects.addEventListener(MObjectEvent.OPEN_OBJECT_DETAILS, openObjectDetails);
	
	mObjectDetails.addEventListener("detailsClosed", objectDetailsClosed);
	mObjectDetails.addEventListener(MObjectEvent.DELETE_OBJECT, refreshObjectsByTags);
	mObjectDetails.addEventListener(MObjectEvent.OBJECT_CHANGED, refreshObjectsByTags);

	mWS.getTagTree();
	mWS.getAlbumObjects(1);	
}

private function callBackGetUsers(event: GetUsersResultEvent): void {
	users = event.result as ArrayCollection;
}		
	
private function callBackGetTagTree(event: GetTagTreeResultEvent): void {
	tags = event.result;
}

private function callBackGetAlbumObjects(event: GetAlbumObjectsResultEvent): void {
	objects = event.result;
}

private function callBackGetObjectsByTag(event: GetObjectsByTagResultEvent): void {
	objectsByTag = event.result;
}			

private function callBackError(event: FaultEvent): void {
	Alert.show(event.fault.message);
}

private function refreshObjectsByTags(event: Event): void {
	if (treeTags.selectedItem)
		mWS.getObjectsByTag((treeTags.selectedItem as TagTreeInfo).ID, cbIncludeSubTags.selected);
}

private function refreshTags(event: Event): void {
	mWS.getTagTree();
}

private function tabIndexChanged(event: IndexChangedEvent): void {
	if (event.relatedObject == frmByTags)
		mWS.getAlbumObjects(1);
}

private function objectDetailsClosed(event: Event): void {
	vsMainView.selectedChild = tabNavMain; 
	mObjectDetails.detailsObject = null;
}

private function openObjectDetails(event: MObjectEvent): void {
	vsMainView.selectedChild = mObjectDetails;
	mObjectDetails.detailsObject = event.mObject;
}